// pages/cart/cart.js
const app = getApp()
var api = require('../../utils/api.js')
var util = require('../../utils/util.js');
Page({

  /**
   * 页面的初始数据
   */
  data: {
    items:[],
    chooseAll:false,
    totalPrice:0
  },

  /**
   * 生命周期函数--监听页面加载
   */
  onLoad: function (options) {
      
  },
  onShow:function(){
    this.getCartList();
  },

  /**
   * 页面相关事件处理函数--监听用户下拉动作
   */
  onPullDownRefresh: function () {
  
  },
  //手指触摸动作开始 记录起点X坐标
  touchstart: function (e) {
    //开始触摸时 重置所有删除
    this.data.items.forEach(function (v, i) {
      if (v.isTouchMove)//只操作为true的
        v.isTouchMove = false;
    })
    this.setData({
      startX: e.changedTouches[0].clientX,
      startY: e.changedTouches[0].clientY,
      items: this.data.items
    })
  },
  //滑动事件处理
  touchmove: function (e) {
    var that = this,
      index = e.currentTarget.dataset.index,//当前索引
      idx = e.currentTarget.dataset.idx,//当前索引
      startX = that.data.startX,//开始X坐标
      startY = that.data.startY,//开始Y坐标
      touchMoveX = e.changedTouches[0].clientX,//滑动变化坐标
      touchMoveY = e.changedTouches[0].clientY,//滑动变化坐标
      //获取滑动角度
      angle = that.angle({ X: startX, Y: startY }, { X: touchMoveX, Y: touchMoveY });
    for (var n = 0; n < that.data.items.length;n++){
      if(n==index){
        that.data.items[index].list.forEach(function (v, i) {
          v.isTouchMove = false
          //滑动超过30度角 return
          if (Math.abs(angle) > 30) return;
          if (i == idx) {
            if (touchMoveX > startX) { //右滑
              v.isTouchMove = false
            }
            else { //左滑
              v.isTouchMove = true
            }
          }
        })
      }else{
        that.data.items[n].list.forEach(function (v, i) {
          v.isTouchMove = false
        })
      }
    }
    
    //更新数据
    that.setData({
      items: that.data.items
    })
  },
  /**
   * 计算滑动角度
   * @param {Object} start 起点坐标
   * @param {Object} end 终点坐标
   */
  angle: function (start, end) {
    var _X = end.X - start.X,
      _Y = end.Y - start.Y
    //返回角度 /Math.atan()返回数字的反正切值
    return 360 * Math.atan(_Y / _X) / (2 * Math.PI);
  },
  getCartList:function(){
    var that = this;
    api.POST({
      params:"",
      url: app.globalData.base_url + 'shoppingcart/goodsList',
      success: function (res) {
        if (util.isEmpty(res.data.code)) {
          var items = res.data.data.list;
          for(var i=0;i<items.length;i++){
            items[i].checked = false
            for (var n = 0; n < items[i].list.length; n++){
              items[i].list[n].checked = false
            }
          }
          that.setData({
            'items': items,
            "chooseAll": false,
            "totalPrice":0
          })
        }
      },
      fail: function (fail) {
        util.showError("登录失败，请检查网络");
      }
    })
  },
  checkboxChange:function(e){
    var indexs = e.currentTarget.dataset.index;
    var shop_id = this.data.items[indexs].list[0].shop_id
    if (shop_id){
      this.setData({
        shop_id: shop_id
      })
    }
    
    // console.log('checkbox发生change事件，携带value值为：', e.detail.value)
    var selBox = e.detail.value;
    var itemsBox = this.data.items;

    for (var j = 0; j < itemsBox.length; j++){
      if(j==indexs){
        var items = this.data.items[indexs].list;
        for (var n = 0; n < items.length; n++) {
          var num = 0;
          for (var i = 0; i < selBox.length; i++) {
            var index = selBox[i];
            if (index == n) {
              num++;
            }
          }
          if (num > 0) {
            items[n].checked = true
          } else {
            items[n].checked = false
          }
        }
        if (selBox.length == items.length) {
          itemsBox[j].checked = true;
        } else {
          itemsBox[j].checked = false;
        }
        itemsBox[indexs].list = items;
      }else{
        var items = this.data.items[j].list;
        for (var n = 0; n < items.length; n++) {
            items[n].checked = false
        }

        itemsBox[j].list = items;
        itemsBox[j].checked=false;
      }
    }



    this.setData({
      'items': itemsBox
    })

    this.totalPrice();
  },

  // 购物车全选操作
  chooseAll:function(e){
    var indexs = e.currentTarget.dataset.index;
    var checked = e.currentTarget.dataset.checked;

    var shop_id = this.data.items[indexs].list[0].shop_id
    if (shop_id) {
      this.setData({
        shop_id: shop_id
      })
    }

    checked = !checked;
    var itemsBox = this.data.items;

    for (var j = 0; j < itemsBox.length; j++) {
      if (j == indexs) {
        var items = this.data.items[j].list;
        for (var n = 0; n < items.length; n++) {
          items[n].checked = checked
        }

        itemsBox[j].list = items;
        itemsBox[j].checked = checked;
      } else {
        var items = this.data.items[j].list;
        for (var n = 0; n < items.length; n++) {
          items[n].checked = false
        }

        itemsBox[j].list = items;
        itemsBox[j].checked = false;
      }
    }

    this.setData({
      'items': itemsBox
    })



    this.totalPrice();
  },
  // 购物车数量增加
  addCart:function(e){
    var index = e.currentTarget.dataset.index;
    var idx = e.currentTarget.dataset.idx;
    var items = this.data.items;
    var num = items[index].list[idx].num;
    var id = items[index].list[idx].id;
    num++;
    this.editorCart(id, num, index, idx);
  },
  // 购物车数量减少
  minusCart: function (e) {
    
    var index = e.currentTarget.dataset.index;
    var idx = e.currentTarget.dataset.idx;
    var items = this.data.items;
    var num = items[index].list[idx].num;
    var id = items[index].list[idx].id;
    num--;
    this.editorCart(id, num, index, idx);
  },
  //修改购物车数量
  editorCart: function (id, num, index, idx){
    var params = new Object()
    var that = this;
    var items = this.data.items;
    params.num = num;
    params.id = id;
    api.POST({
      params: params,
      url: app.globalData.base_url + 'shoppingcart/modGoods',
      success: function (res) {
        if (util.isEmpty(res.data.code)) {
          items[index].list[idx].num = num;
          that.setData({
            items: items
          })
          that.totalPrice();
        }

      },
      fail: function (fail) {
        util.showError("../../../", "获取失败，请检查网络");
      }
    })
  },
  // 商品价格计算
  totalPrice:function(){
    var totalPrice = 0;
    var items = this.data.items;
    for (var i = 0; i < items.length; i++){
      for (var n = 0; n < items[i].list.length;n++){
        if (items[i].list[n].checked) {
          var total = (items[i].list[n].vip_price * items[i].list[n].num).toFixed(2)
          totalPrice = (totalPrice / 1 + total / 1).toFixed(2)
        }
      }
    }
    this.setData({
      totalPrice: totalPrice
    })
  },


// 提交购物车
  submitOrder:function(){
    var items = this.data.items;
    // console.log(items);
    var orderList = [];
    for(var i=0;i<items.length;i++){
      for(var n=0;n<items[i].list.length;n++){
        if (items[i].list[n].checked) {
          var box = new Object();
          box.num = items[i].list[n].num;
          box.sku_code = items[i].list[n].sku_code;
          box.current_price = items[i].list[n].vip_price;
          box.gname = items[i].list[n].gname;
          box.image = items[i].list[n].img;
          box.degree = items[i].list[n].degree;
          box.degree_unit = items[i].list[n].degree_unit;
          box.volume = items[i].list[n].volume;
          box.volume_unit = items[i].list[n].volume_unit;
          box.total = (items[i].list[n].vip_price * items[i].list[n].num).toFixed(2);
          orderList.push(box);
        }
      }
      
    }

    if (orderList.length>0){
      wx.setStorageSync('orderList', orderList);
      if(this.data.shop_id>0){
        wx.navigateTo({
          url: '../order/order?shop_id=' + this.data.shop_id
        })
      }else{
        wx.navigateTo({
          url: '../order/order'
        })
      }
      
    }else{
      util.showError("请选择商品");
    }
    

  },
// 删除购物车商品
  deleteCart:function(e){
    var that = this;
    var index = e.currentTarget.dataset.index;
    var idx = e.currentTarget.dataset.idx;
    var items = this.data.items;
    var ids = items[index].list[idx].id;
    var params = new Object()
    params.ids=ids;
    api.POST({
      params: params,
      url: app.globalData.base_url + 'shoppingcart/delGoods',
      success: function (res) {
        if (util.isEmpty(res.data.code)) {
          items[index].list.splice(idx, 1);
          for (var i = 0; i < items.length; i++) {
            if (items[i].list.length == 0) {
              items.splice(i, 1);
            }
          }
          that.setData({
            items: items
          })
          that.totalPrice();
        }

      },
      fail: function (fail) {
        util.showError("../../../", "获取失败，请检查网络");
      }
    })
  }
})